﻿using Hyjx.DeliveryService.Objects;
using Hyjx.GanFengLogger;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace Hyjx.DeliveryService
{
    /// <summary>
    /// 应用 Http 功能
    /// </summary>
    internal class AppHttp
    {
        readonly ILogger<Delivery> _logger;
        readonly JsonSerializerOptions _jsonSerializerOptions;

        public AppHttp(ILogger<Delivery> logger)
        {
            _logger = logger;
            _jsonSerializerOptions = new JsonSerializerOptions() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };

        }

        /// <summary>
        /// 上报成品罐中转罐状态
        /// </summary>
        /// <param name="url">基本地址</param>
        /// <param name="args">参数</param>
        internal void ReportStatus(string url, ReportStatusArgs args)
        {
            HttpPostAsync($"{url}", args.DeviceCode ?? string.Empty, 212, args);
        }

        async void HttpPostAsync(string url, string deviceCode, int interfaceId, object args)
        {
            try
            {
                using HttpClient http = new();
                var serializerOptions = new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkUnifiedIdeographsExtensionA)
                };
                LogObject log = new() { DeviceCode = deviceCode, InterfaceId = interfaceId, RequestUrl = url, RequestContent = JsonSerializer.Serialize(args) };

                var response = await http.PostAsJsonAsync(url, args); // 提交
                var result = await response.EnsureSuccessStatusCode().Content.ReadFromJsonAsync<GanFengResult>();
                log.ResponseContent = JsonSerializer.Serialize(result, serializerOptions);

                GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                logger.Append("访问成功");
                logger.CompleteWithInformation();
            }
            catch (Exception err)
            {
                Log.Error($"调用MES成品罐中转罐浆料信息上报212接口:{url}异常,信息:{err.Message}");
            }
        }
    }
}
